<template>
  <div class="app-container">
    <div class="courseuser-list">
      <div class="filter-container">
        <div class="filter-item">
          <el-input placeholder="请输入内容"
                    v-model="searchInput"
                    @keyup.enter.native="courseUser"
                    class="input-with-select">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="courseUser"></el-button>
          </el-input>
        </div>

        <div class="filter-item">
          <el-select v-model="searchOptionValue"
                     slot="prepend"
                     @change="courseUser()"
                     placeholder="请选择">
            <el-option v-for="item in searchOption"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </div>
        <div class="filter-item filter-right">
          <el-button type="primary"
                     @click="addDialogBtn">
            添加用户
          </el-button>
        </div>
      </div>

      <el-table :data="tableData"
                style="width: 100%"
                v-loading="loading"
                :header-cell-style="{ background: '#F3F4F7', color: '#555' }">
        <el-table-column prop="loginId"
                         label="账号ID"
                         width="70">
        </el-table-column>
        <el-table-column prop="personName"
                         label="姓名">
        </el-table-column>
        <el-table-column prop="createTime"
                         label="开通时间"
                         width="160">
        </el-table-column>
        <el-table-column label="账号状态"
                         width="100"
                         prop="statusTxt"
                         column-key="statusTxt"
                         :filters="statusOptions"
                         :filter-method="filterStatusHandler"
                         :filter-multiple="false">
        </el-table-column>
        <el-table-column prop="badge"
                         label="徽章数"
                         width="80">
          <template slot-scope="scope">
            {{scope.row.badge}} 枚
          </template>
        </el-table-column>
        <el-table-column prop="badgeUs"
                         label="徽章数(US)"
                         width="100">
          <template slot-scope="scope">
            {{scope.row.badgeUs}} 枚
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         width="300">
          <template slot-scope="scope">
            <el-button type="text"
                       @click="handleGoUserDetail(scope.row.loginId)">查看详情
            </el-button>
            <el-button type="text"
                       class="btn-red"
                       @click="handleDataGiveDialog(scope.row)"
                       v-if="scope.row.status === 0">重设密码
            </el-button>
            <el-popconfirm class="margin-left"
                           :title="
                '确定注销 ID:' +
                scope.row.loginId +
                '，姓名' +
                scope.row.personName +
                '的账号吗？'
              "
                           @onConfirm="userStatusSwitch(scope.row.loginId, scope.row.status)"
                           v-if="scope.row.status === 0">
              <el-button type="text"
                         class="btn-red"
                         slot="reference">
                注销账号
              </el-button>
            </el-popconfirm>
            <div class="btn-end"
                 v-else>已注销</div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-if="pageshow"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="pageSizes"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="添加账号"
               :visible.sync="addDialogVisible"
               :close-on-click-modal="false"
               width="30%"
               center>
      <el-form :model="userAddData"
               :rules="userAddRules"
               status-icon
               ref="userAddData"
               label-width="100px"
               label-position="left"
               class="add-banner-form">
        <el-form-item label="用户名"
                      prop="loginId">
          <el-input type="text"
                    v-model="userAddData.loginId"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名"
                      prop="personName">
          <el-input type="text"
                    v-model="userAddData.personName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    v-model="userAddData.password"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitAddUserForm('userAddData')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="重置密码"
               :visible.sync="resetDialogVisible"
               :close-on-click-modal="false"
               width="30%"
               center>
      <el-form :model="userAddData"
               :rules="userAddRules"
               status-icon
               ref="userAddData"
               label-width="100px"
               label-position="left"
               class="add-banner-form">
        <el-form-item label="用户名">
          {{ userAddData.loginId }}
        </el-form-item>
        <el-form-item label="用户姓名">
          {{ userAddData.personName }}
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    v-model="userAddData.password"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="resetDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submituserUpdateForm('userAddData')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectHeader from '@/components/SelectHeader'
import {
  getCourseUser,
  getAddUser,
  getUserUpdate,
  getUserStatusSwitch,
} from '@/api/table'
import { formatterTime } from '@/utils/common'

export default {
  name: '',
  data() {
    return {
      pageshow: false,
      loading: true,
      //默认参数
      total: 0,
      pageSize: 20,
      currentPage: 1,
      pageSizes: [10, 20, 30, 40],
      tableData: [],
      searchInput: '',
      userData: {
        orderBy: '',
        order: '',
      },
      userAddData: {
        loginId: '',
        personName: '',
        password: '',
      },
      statusOptions: [
        {
          value: '0',
          text: '正常',
        },
        {
          value: '9',
          text: '注销',
        },
      ],
      seachOptionValue: '',
      seachOption: [
        {
          value: '1',
          label: '类别',
        },
        {
          value: '2',
          label: '完成人数',
        },
      ],
      searchOptionValue: 'badge:desc',
      searchOption: [
        { value: 'badge:asc', label: '按徽章数升序' },
        { value: 'badge:desc', label: '按徽章数降序' },
      ],
      seachInput: '',
      addDialogVisible: false,
      resetDialogVisible: false,
      userAddRules: {
        password: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'blur',
          },
        ],
        loginId: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'blur',
          },
        ],
        personName: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    this.courseUser()
  },
  methods: {
    handleSizeChange(e) {
      this.pageSize = e
      this.courseUser()
    },
    handleCurrentChange(e) {
      this.currentPage = e
      this.courseUser()
    },
    addDialogBtn() {
      this.addDialogVisible = true
    },
    submitAddUserForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.getAddUser(formName)
        } else {
          return false
        }
      })
    },
    submituserUpdateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.userUpdate()
        } else {
          return false
        }
      })
    },
    filterStatusHandler(value, row, column) {
      return row.status === Number(value)
    },
    async getAddUser(name) {
      const res = await getAddUser({
        loginId: this.userAddData.loginId,
        personName: this.userAddData.personName,
        password: this.userAddData.password,
      })
      this.courseUser()
      this.addDialogVisible = false
      this.$message({
        type: 'success',
        message: '添加成功',
      })
    },
    async courseUser() {
      this.handleSearchOption()
      this.loading = true
      const res = await getCourseUser({
        search: this.searchInput,
        status: '',
        orderBy: this.userData.orderBy,
        order: this.userData.order,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      })
      this.loading = false
      this.total = res.result.total
      if (this.total <= this.pageSize) {
        this.pageshow = false
      } else {
        this.pageshow = true
      }
      this.tableData = []
      res.result.list.forEach((item) => {
        const data = {}
        data.loginId = item.loginId
        data.personName = item.personName
        data.badge = item.badge
        data.badgeUs = item.badgeUs
        data.status = item.status
        if (item.status === 0) {
          data.statusTxt = '正常'
        } else {
          data.statusTxt = '已注销'
        }
        const newDate = formatterTime(item.createTime)
        data.createTime = newDate
        this.tableData.push(data)
      })
    },
    handleDataGiveDialog(data) {
      this.resetDialogVisible = true
      this.userAddData.loginId = data.loginId
      this.userAddData.personName = data.personName
    },
    handleReset(name) {
      this.$nextTick(() => {
        this.userAddData.loginId = ''
        this.userAddData.personName = ''
        this.userAddData.password = ''
      })
    },
    handleGoUserDetail(id) {
      this.$router.push({
        path: 'userDetail',
        query: {
          id: id,
        },
      })
    },
    async userUpdate() {
      await getUserUpdate({
        loginId: this.userAddData.loginId,
        newPassword: this.userAddData.password,
      })
      this.resetDialogVisible = false
      this.$message({
        type: 'success',
        message: '修改成功',
      })
      this.handleReset('userAddData')
    },
    async userStatusSwitch(id, status) {
      if (status === 0) {
        const res = await getUserStatusSwitch({
          loginId: id,
        })
        this.courseUser()
        this.$message({
          type: 'success',
          message: '注销成功',
        })
      }
    },
    handleSearchOption() {
      this.userData.orderBy = ''
      this.userData.order = ''
      const searchSelect = this.searchOptionValue.split(':')
      const orderName = searchSelect[0]
      const orderType = searchSelect[1]
      this.userData.orderBy = orderName
      this.userData.order = orderType
    },
  },
}
</script>

<style lang="scss" scoped>
.courseuser-list {
  .btn-end {
    display: inline-block;
  }
  .margin-left {
    margin-left: 10px;
  }
}
</style>
<style  lang="scss">
.el-select .el-input {
  width: 180px;
}
</style>
